from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView, ListAPIView

from goods.models import Goods, GoodsCategory, GoodsAlbum
from goods.serializers import RecommendedgoodsSerializer, AlbumSeralizer, TwoParentCategorySerlializer, \
    CategorySerlializer, TwoCategorySerlializer


class Recommended_goods(ListAPIView):
    '''推荐商品'''
    serializer_class = RecommendedgoodsSerializer

    def get_queryset(self):
        return Goods.objects.filter(is_red=1)[:4]


# 获取首页的类别商品  GET  URL:/goods/category/
class Caregory_goods(ListAPIView):
    serializer_class = TwoParentCategorySerlializer

    def get_queryset(self):
        return GoodsCategory.objects.filter(parent_id=0)

        # def get(self, request):
        #     # 获取一级分类
        #     one_category = GoodsCategory.objects.filter(parent_id=0)
        #     serlializer = TwoParentCategorySerlializer(one_category, many=True)
        #
        #     return Response(serlializer.data)



# 详情列表  排序
# URL:/goods/?Category=category_id&ordering=-create_time
class GoodsList(APIView):
    def get(self, request):
        # Cateroty_id int   是  类别id（二级类别）
        # Ordering  str    是  排序关键字(create_time,price)

        # 获取参数 并进行校验
        cateroty_id = request.query_params.get("category")
        ordering = request.query_params.get("ordering")

        # serailizer = GoodsListSerailizer(data)
        # serailizer.is_valid(raise_exception=True)

        # # 获取校验后的数据
        # cateroty_id = serailizer.validated_data['cateroty_id']
        # ordering = serailizer.validated_data['ordering']

        # 二级类别查询商品
        goods = Goods.objects.filter(category_id=cateroty_id).order_by(ordering)

        serlializer = RecommendedgoodsSerializer(goods, many=True)
        return Response(serlializer.data)

# 类别列表
class Goodscategory(APIView):

    def get(self, request, pk):

        # print(pk)
        # 利用一级类别查询二级类别
        category_ids = GoodsCategory.objects.get(id=pk)

        # 如果传入的是二级类别 直接去查询商品数据
        if category_ids.parent_id ==0:
            category_ids.parent_id=pk

        # 二级类别查询商品
        category = GoodsCategory.objects.filter(id=category_ids.parent_id)

        serlializer = TwoCategorySerlializer(category, many=True)
        return Response(serlializer.data[0])


# URL: /goods/(?P<goods_id>\d+)/
# 商品详情页
class GoodsDetil(APIView):
    # serializer_class = RecommendedgoodsSerializer
    #
    #
    # def get_queryset(self, goods_id):
    #
    #     return Goods.objects.get(id=goods_id)

    def get(self,requerst, goods_id):

        # 获取商品数据 序列化返回
        goods = Goods.objects.get(id=goods_id)
        serializer = RecommendedgoodsSerializer(goods)
        return Response(serializer.data)
